using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using SixLabors.Fonts;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Drawing.Processing;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;

namespace Single.Utils
{
    /// <summary>
    /// 图片操作
    /// </summary>
    public static class ThumbnailHelper
    {
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">原图片地址</param>
        /// <param name="thumNailPath">缩略图地址</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="model">生成缩略的模式</param>
        /// <param name="quality">图片质量</param>
        public static void Generate(string originalImagePath, string thumNailPath, int width, int height, TnType model, int quality = 97)
        {
            using var originalImage = Image.Load(originalImagePath);

            int thumWidth = width;      //缩略图的宽度
            int thumHeight = height;    //缩略图的高度
            int x = 0;
            int y = 0;
            int originalWidth = originalImage.Width;    //原始图片的宽度
            int originalHeight = originalImage.Height;  //原始图片的高度

            // 根据模式计算缩略图尺寸
            switch (model)
            {
                case TnType.HW:
                    // 指定高宽缩放，可能变形
                    break;
                case TnType.W:
                    // 指定宽度，高度按照比例缩放
                    thumHeight = originalImage.Height * width / originalImage.Width;
                    break;
                case TnType.H:
                    // 指定高度，宽度按照等比例缩放
                    thumWidth = originalImage.Width * height / originalImage.Height;
                    break;
                case TnType.Cut:
                    // 指定高宽裁剪，居中裁剪
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)thumWidth / (double)thumHeight)
                    {
                        originalHeight = originalImage.Height;
                        originalWidth = originalImage.Height * thumWidth / thumHeight;
                        y = 0;
                        x = (originalImage.Width - originalWidth) / 2;
                    }
                    else
                    {
                        originalWidth = originalImage.Width;
                        originalHeight = originalWidth * height / thumWidth;
                        x = 0;
                        y = (originalImage.Height - originalHeight) / 2;
                    }
                    break;
                case TnType.MW:
                    // 指定最大宽度，超出后按最大宽度缩放
                    if (thumWidth > originalWidth)
                    {
                        thumWidth = originalImage.Width;
                        thumHeight = originalImage.Height;
                    }
                    else
                    {
                        thumHeight = originalImage.Height * width / originalImage.Width;
                    }
                    break;
                case TnType.MH:
                    // 指定最大高度，超出后按最大高度缩放
                    if (thumHeight > originalHeight)
                    {
                        thumWidth = originalImage.Width;
                        thumHeight = originalImage.Height;
                    }
                    else
                    {
                        thumWidth = originalImage.Width * height / originalImage.Height;
                    }
                    break;
            }

            // 创建结果图像
            using var resultImage = new Image<Rgba32>(thumWidth, thumHeight);
            resultImage.Mutate(ctx => ctx.Fill(Color.White));

            if (model == TnType.Cut)
            {
                // 裁剪模式：先从原图裁剪中心部分，然后缩放到目标大小
                using var croppedImage = originalImage.Clone(img =>
                {
                    // 裁剪原图的中心区域
                    img.Crop(new Rectangle(x, y, originalWidth, originalHeight));
                    // 缩放到目标大小
                    img.Resize(new ResizeOptions
                    {
                        Size = new Size(thumWidth, thumHeight),
                        Mode = ResizeMode.Stretch
                    });
                });
                
                // 将裁剪并缩放后的图像绘制到结果图像上
                resultImage.Mutate(ctx => ctx.DrawImage(croppedImage, Point.Empty, 1f));
            }
            else
            {
                // 其他模式：直接缩放原图并居中绘制
                using var resizedImage = originalImage.Clone(img =>
                {
                    img.Resize(new ResizeOptions
                    {
                        Size = new Size(thumWidth, thumHeight),
                        Mode = ResizeMode.Stretch
                    });
                });
                
                // 将缩放后的图像绘制到结果图像上
                resultImage.Mutate(ctx => ctx.DrawImage(resizedImage, Point.Empty, 1f));
            }

            // 保存缩略图，设置JPEG质量
            resultImage.Save(thumNailPath, new JpegEncoder { Quality = quality });
        }

        /// <summary>
        /// 在图片上添加文字水印
        /// </summary>
        /// <param name="syWord">要添加的水印文字</param>
        /// <param name="path">要添加水印的图片路径</param>
        /// <param name="syPath">生成的水印图片存放的位置</param>
        public static void WaterWord(string syWord, string path, string syPath)
        {
            using var image = Image.Load(path);
            
            // 创建FontCollection并尝试加载字体
            var fontCollection = new FontCollection();
            bool hasFont = false;
            FontFamily fontFamily = default;
            
            try
            {
                var fontCollections = fontCollection.AddSystemFonts();
                var families = fontCollections.Families.ToList();
                
                // 尝试加载系统中的Verdana字体
                foreach (var family in families)
                {
                    if (family.Name.Equals("Verdana", StringComparison.OrdinalIgnoreCase))
                    {
                        fontFamily = family;
                        hasFont = true;
                        break;
                    }
                }
                
                // 如果找不到Verdana，使用第一个可用字体
                if (!hasFont && families.Count > 0)
                {
                    fontFamily = families[0];
                    hasFont = true;
                }
            }
            catch
            {
                // 如果出错，设置为无字体
            }
            
            // 如果仍然没有找到字体，尝试使用默认字体
            if (!hasFont)
            {
                try
                {
                    var defaultFontCollection = new FontCollection().AddSystemFonts();
                    var defaultFamilies = defaultFontCollection.Families.ToList();
                    
                    if (defaultFamilies.Count > 0)
                    {
                        fontFamily = defaultFamilies[0];
                        hasFont = true;
                    }
                }
                catch
                {
                    // 如果还是失败，保持无字体状态
                }
            }
            
            // 如果成功获取字体，添加水印
            if (hasFont)
            {
                try
                {
                    // 创建字体
                    var font = fontFamily.CreateFont(12, FontStyle.Regular);
                    
                    // 添加文字水印
                    image.Mutate(ctx => 
                        ctx.DrawText(
                            syWord,
                            font,
                            Color.Red,
                            new PointF(110, 150)));
                }
                catch
                {
                    // 如果字体处理出错，跳过水印
                }
            }
            
            // 保存结果
            image.Save(syPath, new JpegEncoder { Quality = 97 });
        }

        /// <summary>
        /// 在图片上添加图片水印
        /// </summary>
        /// <param name="path">原服务器上的图片路径</param>
        /// <param name="syPicPath">水印图片的路径</param>
        /// <param name="waterPicPath">生成的水印图片存放路径</param>
        public static void WaterPic(string path, string syPicPath, string waterPicPath)
        {
            using var image = Image.Load(path);
            using var waterImage = Image.Load(syPicPath);
            
            // 计算水印位置（居中）
            int x = (image.Width - waterImage.Width) / 2;
            int y = (image.Height - waterImage.Height) / 2;
            
            // 绘制水印
            image.Mutate(ctx => ctx.DrawImage(waterImage, new Point(x, y), 1f));
            
            // 保存结果
            image.Save(waterPicPath);
        }
    }

    /// <summary>
    /// 缩略图生成方式
    /// </summary>
    public enum TnType
    {
        /// <summary>
        /// 指定高宽缩放,可能变形
        /// </summary>
        HW,
        /// <summary>
        /// 指定宽度,高度按照比例缩放
        /// </summary>
        W,
        /// <summary>
        /// 指定高度,宽度按照等比例缩放
        /// </summary>
        H,
        /// <summary>
        /// 指定高宽裁剪,居中裁剪
        /// </summary>
        Cut,
        /// <summary>
        /// 指定最大宽度,超出后按最大宽度缩放
        /// </summary>
        MW,
        /// <summary>
        /// 指定最大高度,超出后按最大高度缩放
        /// </summary>
        MH
    }
}
